package com.byron.pss.web.filter;

import java.io.IOException;
import java.util.Arrays;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.byron.pss.domain.Const;
import com.byron.pss.util.StringUtils;

public class LoginFilter implements Filter {

	// 需要被验证的名单
	private String checked;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		checked = filterConfig.getInitParameter("checked");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// 打散拿到的字符串
		String[] split = checked.split(",");
		// 拿到请求的uri:这里需要注意，必须强转成子类才行
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		String uri = req.getRequestURI();
		// 将数组转成集合，判断请求的uri（要访问的资源）是否包含在需要检查的集合类中，在就判断，不在在就放行。
		if (Arrays.asList(split).contains(uri)) {
			// 需要验证的，拿出Session，如果没有值，直接转到登陆界面
			Object username = req.getSession().getAttribute(
					Const.USERNAME_IN_SESSION);
			if (username == null) {
				resp.sendRedirect(req.getContextPath() + "/unchecked/login.jsp");
				return;
			}
		}
		// 向下传递
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {

	}

}
